var UtilizationBoard = function () {
  var template = /* html */ `
    <div class="utilization-board" v-loading.fullscreen.lock="loading">
      <search-btns ref="searchBtns" :pagination="pagination" :has-search="true" search-btn-text="查询" :popover-width="250"
        search-title="查询条件" @after-leave="afterLeave" v-if="search.deptWork!==null">
        <div slot="search">
          <template v-if="deptWorkName===null">
            <el-cascader clearable filterable v-model="search.deptWork" size="small" :options="deptWorkList" placeholder="部门-车间" separator="-"
              :props="deptWorkProps" style="width:180px"></el-cascader>
            <el-button size="small" type="primary" @click="deptSearchData">查询</el-button>
          </template>
          <span v-else>部门-车间：{{deptWorkName}}</span>
        </div>
      </search-btns>
      <template v-if="utilizationData!==null">
        <template v-if="search.deptWork!==null">
          <div class="utilization-board-year">
            <utilization-month-chart :utilization-data="utilizationData" :pagination="pagination" :search="search"
              :search-fun="searchData">
            </utilization-month-chart>
          </div>
          <div class="utilization-board-month">
            <utilization-day-chart :utilization-data="utilizationData" :pagination="pagination" :search="search"
              :search-fun="searchData">
            </utilization-day-chart>
          </div>
        </template>
        <div v-else class="no-data-div">
          <div class="no-data">
            <div>没有设置车间无法查看稼动率数据</div>
          </div>
        </div>
      </template>
    </div>
  `;

  return {
    mixins: [
      boardRunningMixin,
      boardMixin()
    ],

    data: function () {
      return {
        loading: false,
        utilizationData: null,
        search: {
          year: moment().startOf('year').valueOf(),
          month: moment().startOf('month').valueOf(),
          deptWork: null
        },
        oldDeptWork: null,
        deptWorkProps: {
          checkStrictly: true,
          value: 'id',
          label: 'name',
          children: 'workshops'
        },
        deptWorkList: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setUser().then(function () {
        return self.setUtilizationData().then(function () {
          self.loading = false;
          self.boardRunning();
        });
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUser:function(){
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var deptWork;
          var permissionList = user.permissionList;
          var isManager = user.isManager;
          if (permissionList.indexOf('/superManager') !== -1) {
            isManager = 1;
          }

          var hasSelect = isManager === 1 || user.duty === '1';
          if (hasSelect) {
            deptWork = [];
          } else {
            var deptId = user.deptId;
            if (SysUtil.isEmpty(deptId) || deptId === '0') {
              return user;
            }
            deptWork = [`dept-${deptId}`];
            var workShopId = user.workShopId;
            if (!SysUtil.isEmpty(workShopId) && workShopId !== '0') {
              deptWork.push(`workshop-${workShopId}`);
            }
          }

          self.search.deptWork = _.cloneDeep(deptWork);
          self.oldDeptWork = _.cloneDeep(deptWork);
          if (hasSelect) {
            return user;
          }
          return self.setDeptWorkName(deptWork, user);
        });
      },

      setUtilizationData: function () {
        var self = this;
        return Promise.all([
          this.setMonthUtilization(),
          this.setDayUtilization()
        ]).then(function (res) {
          return self.formatUtilizationData(res);
        });
      },

      setMonthUtilization: function () {
        var search = this.search;
        var year = search.year;
        var postData = {
          year: moment(year).format('YYYY')
        };
        var deptWork = search.deptWork;
        if (deptWork === null) {
          postData.workShop = -1;
        }

        return ajaxRequest('equipment/getEquipmentMonthUseRate', postData).then(function (monthRateList) {
          for (var i = 0; i < monthRateList.length; i++) {
            var monthRate = monthRateList[i];
            if (SysUtil.isEmpty(monthRate.timeName)) {
              monthRate.timeName = `${moment(year).format('YYYY')}-01`;
            }

            if (SysUtil.isEmpty(monthRate.totalTimeOfDay)) {
              monthRate.totalTimeOfDay = 0;
            }
          }
          return {
            year: year,
            monthRateList: monthRateList
          };
        });
      },

      setDayUtilization: function () {
        var search = this.search;
        var month = search.month;
        var postData = {
          month: moment(month).format('YYYY-MM')
        };
        var deptWork = search.deptWork;
        if (deptWork === null) {
          postData.workShop = -1;
        }

        return ajaxRequest('equipment/getEquipmentDailyUseRate', postData).then(function (dayRateList) {
          for (var i = 0; i < dayRateList.length; i++) {
            var dayRate = dayRateList[i];
            if (SysUtil.isEmpty(dayRate.timeName)) {
              dayRate.timeName = `${moment(month).format('YYYY-MM')}-01`;
            }

            if (SysUtil.isEmpty(dayRate.totalTimeOfDay)) {
              dayRate.totalTimeOfDay = 0;
            }
          }
          return {
            month: month,
            dayRateList: dayRateList
          };
        });
      },

      formatUtilizationData: function (res) {
        var utilizationData = this.utilizationData;
        if (utilizationData === null) {
          utilizationData = new UtilizationInfo({
            monthRateData: res[0],
            dayRateData: res[1]
          });
          this.utilizationData = utilizationData;
        } else {
          utilizationData.resetObject({
            monthRateData: res[0],
            dayRateData: res[1]
          });
        }

        this.setDeptWorkList();
        this.toDeptSearchData();
        return utilizationData;
      },

      searchData: function (type) {
        this.loading = true;
        var self = this;
        return this.toSearchData(type).then(function (res) {
          self.formatUtilizationData(res);
          self.pagination.currentPage = 1;
          self.loading = false;
          return true;
        }).catch(function () {
          self.loading = false;
          return false;
        });
      },

      toSearchData: function (type) {
        if (type === undefined) {
          return Promise.all([
            this.setMonthUtilization(),
            this.setDayUtilization()
          ]);
        }

        if (type === 'month') {
          var self = this;
          return this.setMonthUtilization().then(function (monthRateData) {
            var utilizationData = self.utilizationData;
            var equipmentNos = _.uniq(_.map(monthRateData.monthRateList, 'equipmentNo'));
            if (SysUtil.equalsArray(equipmentNos, utilizationData.equipmentList, true)) {
              return [monthRateData, null];
            }

            return self.setDayUtilization().then(function (dayRateData) {
              return [monthRateData, dayRateData];
            });
          });
        }

        if (type === 'day') {
          var self = this;
          return this.setDayUtilization().then(function (dayRateData) {
            var utilizationData = self.utilizationData;
            var equipmentNos = _.uniq(_.map(dayRateData.dayRateList, 'equipmentNo'));
            if (SysUtil.equalsArray(equipmentNos, utilizationData.equipmentList, true)) {
              return [null, dayRateData];
            }

            return self.setMonthUtilization().then(function (monthRateData) {
              return [monthRateData, dayRateData];
            });
          });
        }

        return Promise.resolve([null, null]);
      },

      deptSearchData: function () {
        this.loading = true;
        var self = this;
        setTimeout(function () {
          self.$refs['searchBtns'].closePopover();
          self.pagination.currentPage = 1;
          self.toDeptSearchData();
          self.oldDeptWork = _.cloneDeep(self.search.deptWork);
          self.loading = false;
        }, 500);
      },

      toDeptSearchData: function () {
        var utilizationData = this.utilizationData;
        utilizationData.searchData(this.deptWork);
        this.pagination.totalCount = utilizationData.equipmentList.length;
      },

      setDeptWorkList: function () {
        var deptWorkList = this.utilizationData.getDeptWorkList();
        this.deptWorkList = deptWorkList;
      },

      afterLeave: function () {
        this.search.deptWork = _.cloneDeep(this.oldDeptWork);
      },

      boardRunning:function(){
        this.clearTimeoutList();

        this.resetUtilizationDataRunning();
      },

      resetUtilizationDataRunning: function () {
        this.clearTimeout();
        var tomorrowMoment = moment().add(1, 'day').startOf('day').set({
          hour: 2
        });
        var delayTime = tomorrowMoment.diff(moment());
        var self = this;
        var timeout = setTimeout(function () {
          self.searchData().then(function () {
            self.resetUtilizationDataRunning();
          });
          self.timeoutList[0] = null;
        }, delayTime);
        this.timeoutList[0] = timeout;
      }
    },

    components: {
      SearchBtns: SearchBtns,
      UtilizationMonthChart: UtilizationMonthChart,
      UtilizationDayChart: UtilizationDayChart
    },

    template: template
  };
}();
